package com.shopng.server.functions;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.Declarable;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;

import com.shopng.geode.common.Constants;

public class UtilsFunction implements Function,Declarable
{
  
  private static final long serialVersionUID = -1863303456421313088L;
  
  @Override
  public boolean hasResult()
  {
    return Function.super.hasResult();
  }
  
  @Override
  public void execute(FunctionContext context)
  {
    Map<?, ?> map = (Map<?, ?>)context.getArguments();
    String methodName = (String)map.get(Constants.methodName);
    Object[] args = (Object[])map.get(Constants.args);
    Object result = null;
    try
    {
      UtilsFunction u = new UtilsFunction();
      Method driveMtd = this.getClass().getDeclaredMethod(methodName);
      result = driveMtd.invoke(u,args);
    }
    catch (Exception e)
    {
      context.getResultSender().lastResult(e.getMessage());
    }
    context.getResultSender().lastResult(result);
  }
  
  @Override
  public String getId()
  {
    return UtilsFunction.class.getName();
  }
  /**
   * list all region Names
   * @return
   */
  public List<String> listRegions()
  {
    List<String> regionNames = new ArrayList<>();
    for (Region<?, ?> region : getCache().rootRegions())
    {
      Set<Region<?, ?>> subRegions = region.subregions(true);
      if (subRegions.size() == 0)
      {
        regionNames.add(region.getFullPath());
      }
      for (Region<?, ?> subr : subRegions)
      {
        if (subr.subregions(false).size() == 0)
        {
          regionNames.add(subr.getFullPath());
        }
      }
    }
    return regionNames;
  }
  
  public Cache getCache()
  {
    return CacheFactory.getAnyInstance();
  }

  @Override
  public void init(Properties props)
  {
    
  }
}
